﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using Model;
using BLL;
using Common;
using System.Web.Script.Serialization;

namespace WebPortal.Controllers
{
    public class SysLogController : BaseController
    {

        public ActionResult SysList()
        {
            return View();
        }
        public ActionResult DQList(string dbName)
        {
            PageRole role = new PageRole();
            role.role = SysPublicBLL.GetUserRole(Request.Cookies["MDM_UserName"].Value, dbName);
            return View(role);
        }

        /// <summary>
        /// 系统日志信息
        /// </summary>
        /// <param name="id">日志id</param>
        /// <returns></returns>
        public ActionResult GetItem(string dbName, string id)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            Sys_LogBLL bll = new Sys_LogBLL(loginInfos);
            Sys_Log model = bll.GetInfoById(id);
            return Json(model);
        }
        /// <summary>
        /// DQ日志信息
        /// </summary>
        /// <param name="id">日志id</param>
        /// <returns></returns>
        public ActionResult GetDQItem(string dbName, string id)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            Sys_LogBLL bll = new Sys_LogBLL(loginInfos);
            Sys_DQLog model = bll.GetDQInfoById(id);
            return Json(model);
        }
        /// <summary>
        /// 上次登录信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetLogInfo()
        {
            LoginInfo loginInfos = base.loginInfo();
            Sys_LogBLL bll = new Sys_LogBLL(loginInfos);
            Sys_Log model = new Sys_Log(); ;
            if (Request.Cookies["MDM_UserName"] != null)
            {
                model = bll.GetLogInfo(Request.Cookies["MDM_UserName"].Value);
            } 
            return Json(string.Format("您上次的登陆时间：{0}， 登陆IP：{1}", model.OperationTime, model.OperationIP));
        }
        /// <summary>
        /// 清除系统日志
        /// </summary>
        /// <param name="date">清除日期</param>
        /// <returns></returns>
        public string ClearLog(string dbName, string date)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            Sys_LogBLL bll = new Sys_LogBLL(loginInfos);
            string msg = bll.ClearLog("superadmin", date);
            new SysOperationLog(loginInfos).Log("系统日志查询", Request.UserHostAddress, OperationAction.删除, OperationStatus.成功, "清除操作日志,操作成功", "superadmin");
            return msg;
        }
        /// <summary>
        /// 系统日志列表
        /// </summary>
        /// <param name="collection">提交数据</param>
        /// <returns></returns>
        public ActionResult SysLogList(FormCollection collection, string dbName)
        {
            string OperationResult = Request.Params["OperationResult"];
            string OperationIP = Request.Params["OperationIP"];
            string OperationStatus = Request.Params["OperationStatus"];
            string OperationUser = Request.Params["OperationUser"];
            string TimeFrom = Request.Params["TimeFrom"];
            string TimeTo = Request.Params["TimeTo"];

            int rows = int.Parse(Request.Params["rows"]);
            int page = int.Parse(Request.Params["page"]);
            List<SqlParameter> qList = new List<SqlParameter>();
            List<string> sqlWhere = new List<string>();
            string sql = "select * from [Working_db].[Sys_Operation_Log]";
            string getcount = "select count([GUID]) from [Working_db].[Sys_Operation_Log]";
            if (!string.IsNullOrEmpty(OperationResult))
            {
                qList.Add(new SqlParameter("@OperationResult", OperationResult));
                sqlWhere.Add("OperationResult like '%'+@OperationResult+'%'");
            }
            if (!string.IsNullOrEmpty(OperationIP))
            {
                qList.Add(new SqlParameter("@OperationIP", OperationIP));
                sqlWhere.Add("OperationIP =@OperationIP");
            }
            if (!string.IsNullOrEmpty(OperationStatus))
            {
                qList.Add(new SqlParameter("@OperationStatus", OperationStatus));
                sqlWhere.Add("OperationStatus =@OperationStatus");
            }
            if (!string.IsNullOrEmpty(OperationUser))
            {
                qList.Add(new SqlParameter("@OperationUser", OperationUser));
                sqlWhere.Add("OperationUser like '%'+@OperationUser+'%'");
            }
            if (!string.IsNullOrEmpty(TimeFrom))
            {
                qList.Add(new SqlParameter("@TimeFrom", TimeFrom));
                sqlWhere.Add("OperationTime>=@TimeFrom");
            }
            if (!string.IsNullOrEmpty(TimeTo))
            {
                qList.Add(new SqlParameter("@TimeTo", TimeTo));
                sqlWhere.Add("OperationTime<=@TimeTo");
            }
            if (sqlWhere.Count > 0)
            {
                sql += " where " + string.Join(" and ", sqlWhere.ToArray());
                getcount += " where " + string.Join(" and ", sqlWhere.ToArray());
            }
            sql += " order by [OperationTime] desc offset @Rows * (@PageNum-1) rows fetch next @Rows rows only";
            qList.Add(new SqlParameter("@Rows", rows));
            qList.Add(new SqlParameter("@PageNum", page));
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            Sys_LogBLL bll = new Sys_LogBLL(loginInfos);
            List<Sys_Log> list = bll.GetList(sql, qList.ToArray());//数据列表
            int count = bll.GetListCount(getcount, qList.ToArray());//总记录数
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", count);
            jsonDict.Add("rows", list);
            return Json(jsonDict);

        }
        /// <summary>
        /// DQ日志列表
        /// </summary>
        /// <param name="collection">提交数据</param>
        /// <returns></returns>
        public ActionResult SysDQLogList(FormCollection collection, string dbName)
        {
            string DQName = Request.Params["DQName"];
            string DQMessage = Request.Params["DQMessage"];
            string TimeFrom = Request.Params["TimeFrom"];
            string TimeTo = Request.Params["TimeTo"];

            int rows = int.Parse(Request.Params["rows"]);
            int page = int.Parse(Request.Params["page"]);
            List<SqlParameter> qList = new List<SqlParameter>();
            List<string> sqlWhere = new List<string>();
            string sql = "select [GUID] ,[ParentGUID] ,[DQID]  ,[DQName]  ,[DQMessage] ,[DQTypeID] ,[DQTime] from [Working_db].[Sys_DQLog]";
            string getcount = "select count([GUID]) from [Working_db].[Sys_DQLog]";
            if (!string.IsNullOrEmpty(DQName))
            {
                qList.Add(new SqlParameter("@DQName", DQName));
                sqlWhere.Add("DQName like '%'+@DQName+'%'");
            }
            if (!string.IsNullOrEmpty(DQMessage))
            {
                qList.Add(new SqlParameter("@DQMessage", DQMessage));
                sqlWhere.Add("DQMessage like '%'+@DQMessage+'%'");
            }
            if (!string.IsNullOrEmpty(TimeFrom))
            {
                qList.Add(new SqlParameter("@TimeFrom", TimeFrom));
                sqlWhere.Add("DQTime>=@TimeFrom");
            }
            if (!string.IsNullOrEmpty(TimeTo))
            {
                qList.Add(new SqlParameter("@TimeTo", TimeTo));
                sqlWhere.Add("DQTime<=@TimeTo");
            }
            if (sqlWhere.Count > 0)
            {
                sql += " where " + string.Join(" and ", sqlWhere.ToArray());
                getcount += " where " + string.Join(" and ", sqlWhere.ToArray());
            }
            sql += " order by [DQTime] desc offset @Rows * (@PageNum-1) rows fetch next @Rows rows only";
            qList.Add(new SqlParameter("@Rows", rows));
            qList.Add(new SqlParameter("@PageNum", page));
            Dictionary<String, Object> jsonDict = null;
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            Sys_LogBLL bll = new Sys_LogBLL(loginInfos);
            int count = bll.GetDQListCount(getcount, qList.ToArray());
            List<Sys_DQLog> list = bll.GetDQList(sql, qList.ToArray());//数据列表 

            jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", count);
            jsonDict.Add("rows", list);
            return Json(jsonDict);
        }
        /// <summary>
        /// 清除DQ日志信息
        /// </summary>
        /// <param name="log"></param>
        /// <param name="date">清除日期</param>
        /// <returns></returns>
        public string ClearDQLog(string log, string dbName, string date)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            Sys_LogBLL bll = new Sys_LogBLL(loginInfos);
            string msg = bll.ClearDQLog("superadmin", date);
            new SysOperationLog(loginInfos).Log("DQ日志查询", Request.UserHostAddress, OperationAction.删除, OperationStatus.成功, "清除DQ操作日志,操作成功", "superadmin");
            return msg;
        }

        /// <summary>
        /// 清除etl日志信息
        /// </summary>
        /// <param name="date">清除日期</param>
        /// <returns></returns>
        public string ClearETLLog(string dbName, string date)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            Sys_LogBLL bll = new Sys_LogBLL(loginInfos);
            string msg = bll.ClearETLLog(date);
            new SysOperationLog(loginInfos).Log("DQ日志查询", Request.UserHostAddress, OperationAction.删除, OperationStatus.成功, "清除ETL日志,操作成功", "superadmin");
            return msg;
        }

        /// <summary>
        /// 取dq日志
        /// </summary>
        /// <param name="dbName"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ReadDQLog(string dbName, string id)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            Sys_LogBLL bll = new Sys_LogBLL(loginInfos);
            Sys_DQLog model = bll.GetDQInfoById(id);
            return View(model);
        }

        #region EtlLogList

        public ActionResult EtlLogList(string dbName)
        {
            PageRole role = new PageRole();
            role.role = SysPublicBLL.GetUserRole(Request.Cookies["MDM_UserName"].Value, dbName);
            return View(role);
        }

        public ActionResult SysEtlLogList(FormCollection collection, string dbName)
        {
            Dictionary<String, Object> jsonDict = new Dictionary<string, object>();
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            ETLPara etlPara = (ETLPara)jsSerializer.Deserialize(collection["query"], typeof(ETLPara));
            List<SqlParameter> queryParas = new List<SqlParameter>();

            queryParas.Add(new SqlParameter("@SourceSysGuid", etlPara.SourceSysGuid));
            queryParas.Add(new SqlParameter("@ModelGuid", etlPara.ModelGuid));
            queryParas.Add(new SqlParameter("@TargetSysGuid", etlPara.TargetSysGuid));
            queryParas.Add(new SqlParameter("@TaskName", etlPara.TaskName));
            queryParas.Add(new SqlParameter("@TaskStatus", etlPara.TaskStatus));
            queryParas.Add(new SqlParameter("@TimeFrom", etlPara.TimeFrom));
            queryParas.Add(new SqlParameter("@TimeTo", etlPara.TimeTo));
            queryParas.Add(new SqlParameter("@Rows", collection["rows"].ToString()));
            queryParas.Add(new SqlParameter("@PageNum", collection["page"].ToString()));

            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ETLTaskBLL bll = new ETLTaskBLL(loginInfos);

            IList<ETLTaskLogTrans> list = Common.DBConvert.DataTableToList<ETLTaskLogTrans>(bll.SearchETLTaskLogList(queryParas));
            int count = 0;//总记录数
            if (list.Count > 0)
                count = list[0].Count;
            jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", count);
            jsonDict.Add("rows", list);
            return Json(jsonDict);
        }

        #endregion

        public ActionResult ReadEtlLog(string dbName, string id)
        {
            ETLTaskLogTrans model = null;
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            ETLTaskBLL taskBll = new ETLTaskBLL(loginInfos);
            var dt = taskBll.GetTaskHistoryLogByID(id);
            if (dt != null)
            {
                var list = dt.MapToList<ETLTaskLogTrans>();
                if (list.Count > 0)
                    model = list[0];
            }
            if (model == null)
            {
                model = new ETLTaskLogTrans()
                {
                    TaskName = "日志不存在",
                };
            }
            return View(model);
        }

    }
    /// <summary>
    /// etl列表model
    /// </summary>
    public class ETLTaskLogTrans
    {
        public string GUID { get; set; }
        public string TaskID { get; set; }
        public string TaskName { get; set; }
        public string StepName { get; set; }
        public string CreateUser { get; set; }
        public DateTime StartTime { get; set; }
        public string StartTimeStr
        {
            get
            {
                if (this.StartTime.ToString("yyyy-MM-dd HH:mm:ss") == "1900-01-01 00:00:00")
                    return "";
                else
                    return this.StartTime.ToString("yyyy-MM-dd HH:mm:ss");
            }
        }
        public DateTime EndTime { get; set; }
        public string EndTimeStr
        {
            get
            {
                if (this.EndTime.ToString("yyyy-MM-dd HH:mm:ss") == "1900-01-01 00:00:00")
                    return "";
                else
                    return this.EndTime.ToString("yyyy-MM-dd HH:mm:ss");
            }
        }
        public int RunDuration { get; set; }
        public int TaskStatus { get; set; }
        public string Result { get; set; }
        public DateTime BatchTime { get; set; }
        public string BatchTimeStr { get { return this.BatchTime.ToString("yyyy-MM-dd HH:mm:ss"); } }
        public string TaskListGUID { get; set; }
        public int Count { get; set; }
    }
    public class ETLPara
    {

        public string SourceSysGuid { get; set; }
        public string ModelGuid { get; set; }
        public string TargetSysGuid { get; set; }
        public string TaskName { get; set; }
        public string TaskStatus { get; set; }
        public string TimeFrom { get; set; }
        public string TimeTo { get; set; }
        public int RunDuration { get; set; }
    }
}
